package servlet;
import bean.Mail;
import dao.MailDao;
import util.SearchKeyUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;
import java.util.Random;

@WebServlet(name="mailWriteServlet",urlPatterns = "/mailWriteServlet")
public class mailWriteServlet extends HttpServlet{
    @Override
    protected  void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Mail m=new Mail();
        String type=req.getParameter("type");
        String typeStr[]={"建议","投诉","举报","指南","其他"};
        for (int i=0;i<typeStr.length;++i) {
            if(typeStr[i].equals(type)){
                m.setMailType(i);
            }
        }
        String title=req.getParameter("title");
        m.setMailTitle(title);
        String name=req.getParameter("name");
        m.setName(name);
        String phone=req.getParameter("phone");
        m.setPhone(phone);
        String address=req.getParameter("address");
        m.setAddress(address);
        String email=req.getParameter("email");
        if(email!=null&&email.length()!=0){
            m.setEmail(email);
        }
        String opens=req.getParameter("opens");
        if("是".equals(opens)){
            m.setIspublic(1);
        }else {
            m.setIspublic(0);
        }
        String content=req.getParameter("content");
        if(content!=null&&content.length()!=0){
            m.setContent(content);
        }
        int tmpId=(new Random().nextInt(99999))+1;
        System.out.println(tmpId);
        m.setSearchKey(SearchKeyUtil.getSearchKey(String.valueOf(tmpId),'M'));
        String captcha=req.getParameter("captcha");
        MailDao dao= null;

            dao = new MailDao();
        try {
            dao.mailAdd(m);
        } catch (Exception e) {
            e.printStackTrace();
        }
        req.setAttribute("SearchKey",m.getSearchKey());
        req.getRequestDispatcher("/mailbox/mailAddSuccess.jsp").forward(req,resp);
    }
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req,resp);
    }
}